package com._dev.social.controller;


import com._dev.social.common.BaseResponse;
import com._dev.social.common.ErrorCode;
import com._dev.social.common.ResultUtils;
import com._dev.social.exception.BusinessException;
import com._dev.social.service.MinioService;
import com._dev.social.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import static com._dev.social.utils.FileUtils.extractFileUrl;

@RestController
@RequestMapping("api/pics")
@CrossOrigin
@Slf4j
public class PicsController {
    @Autowired
    private MinioService minioService;

    @PostMapping("/uploadAvatar")
    public BaseResponse<String> uploadAvatar(MultipartFile file) {
        log.info("上传文件: " + file.getOriginalFilename());
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            if (fileName == null) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件名不能为空");
            }
            // 上传文件到 MinIO
            minioService.upload(file);
            // 获取文件 URL
            String fileUrl = minioService.getFileUrl(fileName);
            log.info("文件 URL: {}", fileUrl);
            // 处理文件扩展名
            String extractedUrl = extractFileUrl(fileUrl);
            return ResultUtils.succeed(extractedUrl);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        }
    }
}
